import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/constans/storage.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/ext.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/http/network_manger.dart';
import 'package:safetymonitor/app/core/utils/app_badge_util.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/log_util.dart';
import 'package:safetymonitor/app/core/utils/storage_util.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/application/corporation_name_entity.dart';
import 'package:safetymonitor/app/data/entities/application/env_company_tree_entity.dart';
import 'package:safetymonitor/app/data/entities/auth/login_entity.dart';
import 'package:safetymonitor/app/data/entities/home/board/get_message_entity.dart';
import 'package:safetymonitor/gen/assets.gen.dart';
import 'package:safetymonitor/modules/home/home_page/monitor/environmental_monitoring/controller.dart';
import 'package:safetymonitor/modules/home/home_page/monitor/safe_production/controller.dart';
import 'package:safetymonitor/modules/home/user/version_info/update_util.dart';
import 'package:safetymonitor/router/app_pages.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class HomePageControl extends GetxController {
  // 知识库
  void goToKnowledgeBase() {
    Get.toNamed(Routes.knowledgeBase);
  }

  // 一企一档
  void goToOneEnterpriseOneFile() {
    Get.toNamed(Routes.oneEnterpriseOneFile);
  }

  // 报警预警（新）
  void goToNewAlarmWarningPage() {
    Get.toNamed(Routes.newAlarmWarningPage);
  }

  // 报警预警(旧2)
  void goToAlarmWarningPage() {
    Get.toNamed(Routes.alarmWarningPage);
  }

  // 预警处置（旧1）
  void goToWarningDisposal() {
    Get.toNamed(Routes.warningDisposal);
  }

  // 值班管理
  void goToDutyManagement() {
    Get.toNamed(Routes.dutyManagement);
  }

  // 视频监控
  void goToVideoMonitoring() {
    Get.toNamed(Routes.videoMonitoring);
  }

  // 设备管理
  void goToDeviceManagement() {
    Get.toNamed(Routes.deviceManagement);
  }

  // 风险承诺
  void goToRiskCommitment() {
    Get.toNamed(Routes.riskCommitment);
  }

  // 评估报告
  void goToAssessmentReport() {
    selectTime();
    //先选时间 在进入
    // getAssessmentReport();
  }

  // 指数评分
  void goToIndexRating() {
    Get.toNamed(Routes.indexRating);
  }

  // 今日警情
  void goTodayPage() {
    Get.toNamed(Routes.todayPage)?.then((_) {
      //刷星
      getAlarmCount();
    });
  }

  // 公告板
  void goToNoticeBoard() {
    Get.toNamed(Routes.noticeBoard)?.then((value) {
      //刷新公告
      _getData();

      //刷新获得当前用户的未读站内信数量
      // _getUnreadCount();
    });
  }

  // 统计分析
  void goToStatisticalAnalysis() {
    Get.toNamed(Routes.statisticalAnalysisPage);
  }

  // 设备报备
  void goToMaintenance() {
    Get.toNamed(Routes.maintenancePage);
  }

  GetMessageEntity getNoticeBoardEntity = GetMessageEntity(
    readStatus: false,
    templateContent: '通知公告',
  );

  ///获取账号的当前公司名字
  String? userCompanyName;

  /// 公司列表
  List<CorporationNameEntity> nameList = [];

  /// systemFlag，系统类型标识，1-安全 2-环保 3-二者都有
  int? systemFlag;
  int? userCompanyId;

  /// 中间的模块列表
  List<ModuleEntity> middleList = [];

  /// 后端返回的所有数据
  List<LoginAppMenuCodes> middleListAll = [];

  @override
  void onInit() {
    super.onInit();
    //获取当前公司id
    userCompanyId = UserManager.getUserCompanyId();
    //获取当前公司显示环境还是安全
    systemFlag = UserManager.getUser()?.systemFlag;
    _init();
  }

  _init() async {
    final bool isNetWork = await NetworkManager.checkNetworkType();
    _getDepartmentList();
    _getData();
    _getUnreadCount();
    evnCompanyTree1();
    evnCompanyTree2();
    getPermissionInfo();
    // 获取新版本信息
    UpdateUtil.checkUpdate();
  }

  /// 获取公司列表
  void _getDepartmentList() async {
    final res = await HttpUtil().generateGetRequest<List<CorporationNameEntity>>(Interface.deptList, queryParameters: {
      'flag': 2,
    }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        nameList = result.data!;
      }
    });
  }

  /// 获取通知公告列表
  void _getData() async {
    final res = await HttpUtil().generateGetRequest<List<GetMessageEntity>>(Interface.getNoticeList, queryParameters: {
      'pageNo': 1,
      'pageSize': 20,
    }).execute();

    if (res.isSucceed) {
      if (res.data!.isNotEmpty) {
        getNoticeBoardEntity = res.data!.first;
      }
      // _addWebSocket();
      update();
    }
  }

  WebSocketChannel? channel;

  // 添加websocket
  void _addWebSocket() {
    AppLogger.log('---添加websocket ${Interface.wsUrl}?token=${UserManager.getToken()?.replaceAll('Bearer ', '')}');
    final wsUrl = Uri.parse('${Interface.wsUrl}?token=${UserManager.getToken()?.replaceFirst('Bearer ', '')}');
    channel = WebSocketChannel.connect(wsUrl);

    /// 返回: {"type":"demo-message-receive","content":"{\"fromUserId\":1,\"text\":\"草泥马\",\"single\":true}"}
    channel!.stream.listen((message) {
      AppLogger.log('---$message');

      if (message.toString().contains('content')) {
        final map = jsonDecode(message.toString());

        if (map is Map<String, dynamic>) {
          final con = jsonDecode(map['content'].toString());

          if (con is Map<String, dynamic>) {
            AppLogger.log('----${con['text']}');
            getNoticeBoardEntity = GetMessageEntity(
              readStatus: false,
              templateContent: con['text'].toString() ?? '通知公告',
            );
            //刷新获得当前用户的未读站内信数量
            _getUnreadCount();
            update();
          }
        }
      }
    });
  }

  // 关闭websocket
  void _closeWebSocket() {
    if (channel != null) {
      channel!.sink.close();
      channel = null;
    }
  }

  @override
  void dispose() {
    _closeWebSocket();
    super.dispose();
  }

  RxInt unreadCount = 0.obs;

  ///刷新获得当前用户的未读站内信数量
  void _getUnreadCount() async {
    final res = await HttpUtil().generateGetRequest(Interface.getUnreadCount).execute();
    if (res.isSucceed) {
      if (res.data != null) {
        unreadCount.value = res.data as int; //数量
        AppBadgeUtil.setBadgeCount(unreadCount.value);
      }
      update();
    }
  }

  ///获取流的返回数据 并下载到本地  再打开
  Future<void> getAssessmentReport() async {
    SmartDialog.showLoading(msg: '正在下载...');
    final dio = Dio(BaseOptions(
      headers: {'Authorization': UserManager.getToken()},
      responseType: ResponseType.bytes,
    ));
    AppLogger.log('----${Interface.downAlarmReport}?beginTime=$startDate&endTime=$endDate');
    final response = await dio.get(
      // Interface.downAlarmReport+'?beginTime=2024-07-01%2000%3A00%3A00&endTime=2024-08-10%2023%3A59%3A59',
      '${Interface.downAlarmReport}?beginTime=$startDate&endTime=$endDate',
      options: Options(
        responseType: ResponseType.bytes,
      ),
    );
    if (response.statusCode == 200) {
      try {
        ///应用程序可以放置以下数据的目录路径
        ///用户生成的，或者您的应用程序无法重新创建的。
        final directory = await getApplicationDocumentsDirectory();
        final file = File('${directory.path}/alarm_report.pdf');
        await file.writeAsBytes(response.data as List<int>);
        //打开
        try {
          await OpenFilex.open(file.path, type: 'application/pdf');
        } catch (e) {
          // 处理错误，比如提示用户安装 PDF 阅读器
          AppToast.showWarning('无法打开 PDF 文件，请安装一个支持 PDF 的应用。');
        }
      } catch (_) {
        AppToast.showWarning('文件打开失败！');
      } finally {
        SmartDialog.dismiss();
      }
    }
  }

  /// 值班结束时间
  String endDate = '';

  /// 值班开始时间
  String startDate = '';

  /// 默认开始时间  null传入也是开始时间
  selectTime() async {
    final DateTimeRange? picked = await showDateRangePicker(
      context: Get.context!,
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
      currentDate: DateTime.now(),
      saveText: '确定',
    );

    if (picked != null) {
      startDate = picked.start.toStr;
      endDate = picked.end.toStr;
      getAssessmentReport();
    }
  }

  List<EnvCompanyTreeEntity> envCompanyTreeEntity1 = [];
  List<EnvCompanyTreeEntity> envCompanyTreeEntity2 = [];

  ///1为安全
  ///2为环境
  //获取公司树结构(筛选) 4个筛选 组装  - companyType 系统类型（0都有 1为安全 2 为环境）
  Future<List<EnvCompanyTreeEntity>?> evnCompanyTree1() async {
    final res = await HttpUtil().generateGetRequest<List<EnvCompanyTreeEntity>>(Interface.evnCompanyTree, queryParameters: {
      'dataType':1,
    }).execute();
    if (res.isSucceed) {
      if (res.data != null) {
        envCompanyTreeEntity1 = res.data!;
        Get.find<SafeProductionController>().update();
        return res.data;
      }
    }
    return null;
  }
  ///1为安全
  ///2为环境
  //获取公司树结构(筛选) 4个筛选 组装  - companyType 系统类型（0都有 1为安全 2 为环境）
  Future<List<EnvCompanyTreeEntity>?> evnCompanyTree2() async {
    final res = await HttpUtil().generateGetRequest<List<EnvCompanyTreeEntity>>(Interface.evnCompanyTree, queryParameters: {
      'dataType':2,
    }).execute();
    if (res.isSucceed) {
      if (res.data != null) {
        envCompanyTreeEntity2 = res.data!;
        Get.find<EnvironmentalMonitoringController>().update();
        return res.data;
      }
    }
    return null;
  }
  final alarmCount = ValueNotifier(0);

  /// 安全监测 - app -获取今日报警数
  Future<void> getAlarmCount() async {
    final resp = await HttpUtil()
        .generateGetRequest<int>(
          Interface.getTodayAlarmCount,
        )
        .execute(isShowToast: false);
    if (resp.isSucceed && resp.data != null) {
      alarmCount.value = resp.data!;
    }
  }

  /// 获取权限配置数据
  Future<void> getPermissionInfo() async {
    middleList.addAll([
      ModuleEntity(
        name: '知识库',
        icon: Assets.svg.iconHomeLore,
        show: true,
        onTap: goToKnowledgeBase,
        appMenuNameCode: 'knowledge_base',
      ),
      ModuleEntity(
        name: '一企一档',
        icon: Assets.svg.iconHomeFile,
        show: true,
        onTap: goToOneEnterpriseOneFile,
        appMenuNameCode: 'one_enterprise_one_file',
      ),
      ModuleEntity(
        name: '视频监控',
        icon: Assets.svg.iconHomeMonitor,
        show: true,
        onTap: goToVideoMonitoring,
        appMenuNameCode: 'video_screen',
      ),
      ModuleEntity(
        name: '统计分析',
        icon: Assets.svg.iconHomeStatistical,
        show: true,
        onTap: goToStatisticalAnalysis,
        appMenuNameCode: 'statistical_analysis',
      ),
      ModuleEntity(
        name: '监测设备',
        icon: Assets.svg.iconHomeDevice,
        show: true,
        onTap: goToDeviceManagement,
        appMenuNameCode: 'device_management',
      ),
      ModuleEntity(
        name: '风险承诺',
        icon: Assets.svg.iconHomePromise,
        show: true,
        onTap: goToRiskCommitment,
        appMenuNameCode: 'risk_commitment',
      ),
      ModuleEntity(
        name: '评估报告',
        icon: Assets.svg.iconHomeReport,
        show: true,
        onTap: goToAssessmentReport,
        appMenuNameCode: 'assessment_report',
      ),
      ModuleEntity(
        name: '综合评分',
        icon: Assets.svg.iconHomeScore,
        show: true,
        onTap: goToIndexRating,
        appMenuNameCode: 'index_rating',
      )
    ]);
    final LoginEntity? userInfo = StorageUtil.getEntity<LoginEntity>(StorageConstants.appMiddleModuleList);
    if (userInfo != null) {
      middleList.removeWhere((element) => !userInfo.appMenuCodes.map((e) => e.appMenuNameCode).toList().contains(element.appMenuNameCode));
    }
    update();
    final res = await HttpUtil().generatePostRequest<LoginEntity>(Interface.appLogin, data: {
      'username': UserManager.getUsername(),
      'password': UserManager.getPassword(),
    }).execute(
      isShowLoading: false,
    );
    res.onSuccess((result) async {
      if (result.data != null) {
        middleListAll = result.data?.appMenuCodes ?? [];
        //appMenuCodes和middleList下appMenuNameCode标识一样取交集
        middleList.removeWhere((element) => !result.data!.appMenuCodes.map((e) => e.appMenuNameCode).toList().contains(element.appMenuNameCode));
        StorageUtil.setJSON(StorageConstants.appMiddleModuleList, result.data);
      }
      update();
    });
  }
}

/// 模块的实体类
/// 名字,图标,是否显示,点击事件
class ModuleEntity {
  ModuleEntity({required this.name, required this.icon, required this.onTap, this.show = false, this.appMenuNameCode = ''});

  /// 名字
  final String name;

  /// 图标
  final String icon;

  /// 是否显示
  final bool show;

  /// 标识 appMenuNameCode
  final String appMenuNameCode;

  /// 跳转事件
  final void Function() onTap;

  @override
  String toString() {
    return 'ModuleEntity{name: $name, icon: $icon, show: $show, onTap: $onTap, appMenuNameCode: $appMenuNameCode}';
  }
}
